/**
 * Created by leo on 5/31/16.
 */

var express = require('express');
var router = express.Router();
var Device = require('../models/device');
var net = require('net');
var request = require('request');

router.get('/', function(req, res) {
    Device.getDevices(function(err, devices) {
        if (err) {
            //console.log(err);
        }
        res.json(devices);
    });
});

router.get('/:_id', function(req, res) {
    Device.getDeviceById(req.params._id, function(err, device) {
        if (err) {
            //console.log(err);
        }
        res.json(device);
    });
});

router.post('/', function(req, res) {
    var device = req.body;
    Device.addDevice(device, function(err, device) {
        if (err) {
            //console.log(err);
        }
        var name = device != null ? device.name : "";
        if (name) {
            console.log('成功关联设备 "' + name  + '"');
        }
        res.json(device);
    });
});

router.put('/:_id', function (req, res) {
    var id = req.params._id;
    var device = req.body;
    Device.updateDevice(id, device, {}, function(err, device) {
        if (err) {
            throw err;
        }
        res.json(device);
    });
});

router.delete('/:_id', function (req, res) {
    var id = req.params._id;
    Device.getDeviceById(id, function(err, device) {
        if (err) {
            //console.log(err);
        }
        Device.removeDevice(id, function(err, device) {
            if (err) {
                //console.log(err);
            }
        });
        console.log('成功取消关联设备 "' + device.name + '"');
        res.json(device);
    });

});

//******************* send command to android
function pushMsg(req, res) {
    var id = req.params._id;
    var command = req.params._command;
    // 设备命令发送成功，推送给手机端
    var options = {
        url: 'https://api.bmob.cn/1/push',
        method: 'POST',
        json: true,
        headers: {
            'X-Bmob-Application-Id': 'db6febe3dd41bebea8b350b8cc9b2278',
            'X-Bmob-REST-API-Key': 'd367b8d481c2e6ec6b7af2eafe3d40d3',
            'Content-Type': 'application/json'
        },
        body: {
            "where":{
                "deviceType":"android"
            },
            "data": {
                "id": id,
                "command": command
            }
        }
    };
    request(options, function (err, response, body) {
        if (!err) {
            console.log("成功向设备 \"" + id + "\" 发起命令 [" + command + "]");
            Device.findOneAndUpdate({_id: id}, {
                $set: {
                    status: command == "on"
                }
            }).exec(function(err, device) {
                if (err) {
                    console.log(err);
                    //return;
                }

                console.log("设备状态 [" + command + "] 保存成功");
                res.json({
                    "id": id,
                    "command": command
                });
            })
        }
    });
}

router.get('/:_id/:_command', function (req, res) {
    var source = req.get('Source');
    var id = req.params._id;
    var command = req.params._command;

    if (source == 'app') {
        // App->设备，建一个Socket Client来请求本地Socket
        var client = new net.Socket();
        client.connect(9999, '127.0.0.1', function() {
            client.write(command)
        });

        client.on('data', function(data) {
            // if (data == 'success') {
            console.log('\<Socket\> 成功收到设备返回的数据');
            //pushMsg(req, res);
            // }
            res.json({
                "id": id,
                "command": command
            });
            client.destroy();
        });

        client.on('close', function() {
            //console.log('\<Socket\> App client关闭');
        });
    } else {
        // 设备->App，直接Bmob推送
        pushMsg(req, res);
    }


});

module.exports = router;